package com.ps.aspect;

import com.ps.exception.JsonResultException;
import com.ps.model.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


// 提前异常处理 比如get，post请求参数格式不对，会抛出一个异常
@Slf4j
@RestControllerAdvice
public class RestExceptionAspect {

    // 抛出异常时希望返回给前台
    @ExceptionHandler(JsonResultException.class)
    public R handleJsonResultException(JsonResultException e) {
//        recordUserAction(e);
        return R.fail(e.getMessage());
    }

    // 请求方法有误
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return R.fail("请求方法有误");
    }

    // 校验不通过    我要你传QQ邮箱  qq.com    ---->   "fwefwefwefwef"
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String error = bindingResult.getFieldErrors().get(0).getDefaultMessage();
        return R.fail(error);
    }

    // @RequestParam没有匹配到值
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public R handle(MissingServletRequestParameterException e) {
        log.error(e.getMessage(), e);
        return R.fail("get参数有误");
    }

    // @RequestBody没有匹配到值
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R handle(HttpMessageNotReadableException e) {
        log.error(e.getMessage(), e);
        return R.fail("post参数有误");
    }

}
